<?php

namespace common\models\sys;

use common\models\AdminModel;
use izyue\admin\models\Log;
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\Url;

/**
 * This is the model class for table "sys_opration_log".
 *
 * @property integer $id
 * @property string $route
 * @property string $description
 * @property integer $created_at
 * @property integer $user_id
 */
class SysOprationLog extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sys_opration_log';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['description'], 'string'],
            [['created_at', 'user_id'], 'integer'],
            [['route','title'], 'string', 'max' => 255],
            [['time'], 'string', 'max' => 500],
            [['picture'], 'string', 'max' => 2000],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'route' => '地址',
            'description' => '描述',
            'created_at' => '修改时间',
            'user_id' => '操作人',
            'picture' => '图片更改',
            'time' => '时间更改',
            'title' => '标题'
        ];
    }


    public static function write($event)
    {
        // 排除日志表自身,没有主键的表不记录（没想到怎么记录。。每个表尽量都有主键吧，不一定非是自增id）
        if($event->sender instanceof SysOprationLog || !$event->sender->primaryKey()) {
            return;
        }
        if($event->sender instanceof Log  || !$event->sender->primaryKey()) {
            return;
        }

        $desc = '';
        $timedesc = [];
        $picdesc = [];
        $label = $event->sender->attributeLabels();
        // 显示详情有待优化,不过基本功能完整齐全
        if ($event->name == ActiveRecord::EVENT_AFTER_INSERT) {
            $title = "%s新增了%s“%s”";
            $description = "%s";
        } elseif($event->name == ActiveRecord::EVENT_AFTER_UPDATE) {
            $title = "%s修改了%s“%s”";
            $description = "%s";
        } else {
            $title = "%s删除了%s“%s”";
            $description = "%s";
            $desc = $label[$event->sender->uselog['mainfield']].'=@='.$event->sender->getAttribute($event->sender->uselog['mainfield']).'=@=\'\'';
        }
//        var_dump($event);exit;
        if (!empty($event->changedAttributes)) {
            foreach($event->changedAttributes as $name => $value) {
                if(!array_key_exists($name,$label)){        //没有给字段别名的，忽略
                    continue ;
                }
                if(!in_array($name,$event->sender->uselog['unsetfiled'])){        //不记录不需要记录的字段
                    if(in_array($name,$event->sender->uselog['timefield'])){
                        $timedesc[] = $label[$name] . '=@=' . $value . '=@=' . $event->sender->getAttribute($name);
                        continue;
                    }
                    if(in_array($name,$event->sender->uselog['picturefield'])){
                        $picdesc[] = $label[$name] . '=@=' . $value . '=@=' . $event->sender->getAttribute($name);
                        continue;
                    }
                    $desc .= $label[$name] . '=@=' . $value . '=@=' . $event->sender->getAttribute($name) . '###';
                }
            }
            $desc = substr($desc, 0, -1);
        }
        $userName = Yii::$app->user->identity->username;
        $tableName = $event->sender->uselog['tabcomment'];
        $title = sprintf($title, $userName, $tableName, $event->sender->getAttribute($event->sender->uselog['mainfield']));
        $description = sprintf($description, $desc);

        $route = Url::to();
        $userId = Yii::$app->user->id;
        $ip = ip2long(Yii::$app->request->userIP);
        $time = $timedesc?implode(',',$timedesc):'';
        $picture = $picdesc?implode(',',$picdesc):'';
        $data = [
            'route' => $route,
            'description' => $description,
            'user_id' => $userId,
            'ip' => $ip,
            'time' => $time,
            'picture' => $picture,
            'title' => $title,
        ];
        if(empty($description)){
            return;
        }
        $model = new SysOprationLog();
        $model->setAttributes($data);
        $model->save();
    }




    public function beforeSave($insert)
    {
        $this->created_at = time();
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }



    public function getAdmin()
    {
        return $this->hasOne(AdminModel::className(),['id'=>'user_id']);
    }
}
